import {request} from "../../request/index.js";
// pages/goods_detail/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj:{},
    //商品是否被收藏
    isCollect:false
  },

  GoodsInfo:{},
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    let pages=getCurrentPages();
    let currentPage=pages[pages.length-1];
    let options=currentPage.options;
    const {goods_id}=options;
    this.getGoodsDetail(goods_id);
  },
//获取商品详情数据
  async getGoodsDetail(goods_id){
    const goodsObj=await request({url:"/goods/detail",data:{goods_id}});
    this.GoodsInfo=goodsObj;
    //获取缓存商品收藏的数组
    let collect=wx.getStorageSync("collect")||[];
    //判断商品是否被收藏
    let isCollect=collect.some(v=>v.goods_id===this.GoodsInfo.goods_id);
    this.setData({
      goodsObj:{
        goods_name:goodsObj.goods_name,
        goods_price:goodsObj.goods_price,
        goods_introduce:goodsObj.goods_introduce.replace(/.webp/g,'.jpg') ,
        pics:goodsObj.pics,
      },
      isCollect
    })
  },

  handlePrevewImage (e){
    const urls=this.GoodsInfo.pics.map(v=>v.pics_mid);
    const current=e.currentTarget.dataset.url;
    wx.previewImage({
      urls,
      current
    })
  },

  //点击加入购物车
  handleCartAdd(){
    //获取缓存中的购物车 数组
    let cart=wx.getStorageSync('cart')||[];
    //判断商品是否在购物车 数组中
    let index=cart.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
    if (index===-1) {
      //不存在 第一次添加
      this.GoodsInfo.num=1;
      this.GoodsInfo.checked=true;
      cart.push( this.GoodsInfo);
    }else{
      //执行 num++
      cart[index].num++;
    }
    //把购物车重新添加回缓存
    wx.setStorageSync('cart', cart);
    //弹窗提示
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      //TRUE 防止用户疯狂点击按钮，设置1.5秒后才能点击成功
      mask:true
    });
  },
  //点击 商品收藏图标
  handleCollect(){
    let isCollect=false;
    //获取缓存商品的收藏数组
    let collect=wx.getStorageSync('collect')||[];
    //判断商品是否被收藏过
    let index=collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
    if (index!==-1) {     
      //已经收藏过 在数组中删除商品
      collect.splice(index,1);
      isCollect=false;
      wx.showToast({
        title: '取消成功',
        icon:  'success',
        mask:  true
      })
    }else{
      collect.push( this.GoodsInfo);
      isCollect=true;
      wx.showToast({
        title: '收藏成功',
        icon:  'success',
        mask:  true
      })
    }
    //把数据存入缓存
    wx.setStorageSync('collect', collect);
    //修改data属性 isCollect
    this.setData({
      isCollect
    })
  }

})